<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class FocusLib
{
        private $config = array();
        
	function __construct($config = array())
	{
		$ci =& get_instance();
                
		// Helpers
		$ci->load->helper('url_helper');
		
		// Config
		$ci->config->load('focuslib');
                $this->config['providers'] = $ci->config->item('providers');
                $this->config['cron_web_access'] = $ci->config->item('allow_cron_web_access');
	}
        
        /**
         * Allow cron web interface
         * Defined in application/config/focuslib.php
         * @return bool 
         */
        public function allowWebCronJob()
        {
            return $this->config['cron_web_access'];
        }
        
        /**
         * Returns associative array of titles (slug => title);
         */
        public function listProviderTitles()
	{
            return $this->config['providers'];
        }
	
        /**
         * Fecth array of providers
         * @return ArrayObject Array of Concrete Providers.
         */
	public function listProviders()
	{
            $providers = array();
            
            foreach ($this->config['providers'] as $key => $value)
            {
                // Has been implemented?
                if(  file_exists( APPPATH.'/third_party/focus/FProvider' . $key . '.php') )
                    array_push($providers, $this->getProvider( $key ));
            }

            return $providers;
	}
        
        /**
         * Construct concrete ContentProvider
         * @param string $name Provider slug
         * @return FContentProvider Concrete ContentProvider
         */
        public function getProvider($name)
        {
            require_once APPPATH.'/third_party/focus/FContentProviderFactory.php';
            return FContentProviderFactory::build($name);
        }
        
        /**
         * Transforms a single Filters_Model record into a FClientFilter
         * @param type $filterModelObject Filters_Model record
         */
        public function buildClientFilter($filterModelObject)
        {
            require_once APPPATH.'/third_party/focus/FClientFilter.php';
            
            // Create FFilterData Array out of JSON bundle
            $filter_data = array();
            $bundle = json_decode($filterModelObject->filterData);
            
            foreach ($bundle as $provider_data)
            {
                // Instantiate provider
                $provider = $this->getProvider($provider_data->providerName);
                
                if($provider)
                {
                    // Instantiate category
                    $category = $provider->getCategoryByID($provider_data->categoryID);
                    
                    if($category)
                    {
                        // Options
                        $options = array(
                            'providerName' => $provider_data->providerName,
                            'categoryID' => $provider_data->categoryID,
                            'parameters' => '',
                            'currentPosition' => $provider_data->currentPosition
                        );
                        
                        // Get supported params
                        $supported_params = $category->getSupportedParameters();
                        
                        // Fill values
                        foreach ($supported_params as $supported_param)
                        {
                            if( property_exists( $provider_data->parameters, $supported_param->slug ) )
                            {
                                switch ( $supported_param->type )
                                {
                                    case FParameter::TYPE_SINGLE:
                                        $supported_param->value =
                                            $provider_data->parameters->{$supported_param->slug};

                                        break;
                                    
                                    case FParameter::TYPE_BOOL:
                                        $supported_param->value =
                                            $provider_data->parameters->{$supported_param->slug};
                                        
                                        break;
                                    
                                    case FParameter::TYPE_INTERVAL:
                                        $supported_param->value = array(
                                            $provider_data->parameters->{$supported_param->slug}->{'minimum'},
                                            $provider_data->parameters->{$supported_param->slug}->{'maximum'}        
                                        );
                                        
                                        break;
                                    
                                    case FParameter::TYPE_SET:
                                        foreach ($supported_param->value as $value)
                                        {
                                            if(  !strcmp( $value['slug'], $provider_data->parameters->{$supported_param->slug} ) )
                                            {
                                                $supported_param->value = array($value);
                                            }
                                        }

                                        break;
                                }
                            }
                        }
                        
                        $options['parameters'] = $supported_params;
                        $filter_data []= new FFilterData($options);
                    }
                }
                
                
            }
            
            // Construct FClientFilter
            $options = array(
                'ID' => $filterModelObject->ID,
                'clientID' => $filterModelObject->clientID,
                'interval' => $filterModelObject->interval,
                'lastFetched' => $filterModelObject->lastFetched,
                'filterData' => $filter_data,
                'active' => $filterModelObject->active,
                'title' => $filterModelObject->title,
                'sendByEmail' => $filterModelObject->sendByEmail
            );
            
            return new FClientFilter($options);
        }

        public function sendNotificationMessage($options, $content = array())
        {
            require_once APPPATH.'/third_party/focus/FClientFilter.php'; 
            
            $defaults = array(
                'to' => '',
                'firstname' => '',
                'lastname' => '',
                'filter_title' => '',
                'title' => '',
                'body' => ''
            );
            $options['firstname'] = ($options['firstname'] != '') ? $options['firstname'] : 'klient';
            $options = array_merge($defaults, $options);
            
            $options['body'] .=
            "
            Hea " . $options['firstname'] . "!<br /><br />
                
            Leidsime sinu poolt defineeritud sisuallikajälgijale " . $options['filter_title'] . " <strong>" . count($content) . "</strong> vastet:<br /><br /> 
            ";
            
            foreach ($content as $obj) {
                $options['body'] .= 
                "
                    <strong><a href=\"" . $obj->getURL() . "\">" . $obj->getTitle() . "</a></strong><br />
                    " . $obj->getText() . "
                    <br /><br />
                ";
            }
            
            $options['body'] .=
            "
            Kui sa ei soovi edaspidi teavitusi e-posti teel saada, siis külasta Focus keskkonda ning muuda kõnealust sisuallikajägijat.<br /><br />
            
            Tervitades,<br />
            Focus
            ";
            
            // Send an email  
            $ci =& get_instance();
            $ci->load->library("email");  
            $ci->email->set_mailtype("html");
            $ci->email->to($options['to']);
            $ci->email->from("codename.focus@gmail.com", "Focus");
            $ci->email->subject($options['filter_title']);
            $ci->email->message($options['body']);
            $ci->email->send(); 
        }
}

/* End of file FocusLib.php */
/* Location: ./application/libraries/FocusLib.php */
?>